﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Perceiveit.Xml.Tests
{
    public class ExportToCSV<T>
    {
        protected PropertyDescriptorCollection _props;

        public ExportToCSV()
        {
            _props = BuildProperties(typeof(T));
        }

        protected virtual PropertyDescriptorCollection BuildProperties(Type t)
        {
            return TypeDescriptor.GetProperties(t);
        }

        public void Export(string path, IEnumerable<T> items)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path,false))
            {
                this.Export(sw, items);
            }
        }

        private void Export(System.IO.TextWriter sw, IEnumerable<T> items)
        {
            for (int i = 0; i < _props.Count; i++)
            {
                if (i > 0)
                    sw.Write(",");
                sw.Write(_props[i].DisplayName);
               
            }
            sw.WriteLine();
            

            if (null != items)
            {
                foreach (T item in items)
                {
                    this.ExportItem(sw, item);
                    sw.WriteLine();
                }
            }
        }
        
        private static Type stringType = typeof(string);

        private void ExportItem(System.IO.TextWriter sw, T item)
        {
            for (int i = 0; i < _props.Count; i++)
            {
                if (i > 0)
                    sw.Write(",");
                PropertyDescriptor desc = _props[i];

                if (desc.PropertyType.IsValueType)
                {
                    if (desc.PropertyType.IsPrimitive)
                    {
                        sw.Write(desc.GetValue(item));
                    }
                    else
                    {
                        sw.Write('"');
                        sw.Write(desc.GetValue(item));
                        sw.Write('"');
                    }
                }
                else
                {
                    object value = desc.GetValue(item);
                    if(null != value)
                    {
                        sw.Write('"');
                        sw.Write(value);
                        sw.Write('"');
                    }
                }
                
            }
            
        }
    }
}
